const router = require('koa-router')()
const User = require("../models/users")
router.prefix('/userCart');  //二级路由
require("../utils/DateFormat")

//获取用户购物车中的数据
router.post('/', async (ctx, next) => {


    try{
        let userDoc=await User.findOne({userId:ctx.session.user.userId});
        if(!!userDoc){
            ctx.body={
                code:200,
                msg:"",
                result:userDoc.cartList,
            }
        }else{
            ctx.body={
                code:300,
                msg:"查找失败",
                result:"",
            }
        }
    }catch(err){
        ctx.body={
            code:400,
            msg:"系统错误",
            result:"",
        }
    }

})

//修改商品的数量
router.post("/changeGoodsNum",async (ctx,next)=>{

    try{
        /*mongoose 更新数据*/
        let updataUser=await User.update({"userId":ctx.session.user.userId,"cartList.productId":ctx.request.body.productId },{
            "cartList.$.productNum":ctx.request.body.productNum
        })

        if(updataUser.ok == 1){
            ctx.session.user = await User.findOne({userId:ctx.session.user.userId})
            ctx.body={
                code:200,
                msg:"修改成功",
                result:""
            }
        } else{
            ctx.body={
                code:300,
                msg:"修改失败",
                result:""
            }
        }
    }catch(err){
        ctx.body={
            code:400,
            msg:"服务器失败",
            result:""
        }
    }


})

//删除商品
router.post("/delGoods",async (ctx,next)=>{
    let productId=ctx.request.body.productId;
    let newUser = await User.update({
        userId:ctx.session.user.userId
    },{
        $pull:{
            cartList: {
                productId:productId
            }
        }
    })
    if(newUser.ok == 1){

        ctx.body={
            code:200,
            msg:"修改成功",
            result:""
        }
    } else{
        ctx.body={
            code:300,
            msg:"修改失败",
            result:""
        }
    }
})

//修改勾选情况
router.post("/changeChecked",async (ctx,next)=>{

    try{
        /*mongoose 更新数据*/
        let updataUser=await User.update({"userId":ctx.session.user.userId,"cartList.productId":ctx.request.body.productId },{
            "cartList.$.checked":ctx.request.body.checked
        })

        if(updataUser.ok == 1){

            ctx.body={
                code:200,
                msg:"修改成功",
                result:""
            }
        } else{
            ctx.body={
                code:300,
                msg:"修改失败",
                result:""
            }
        }
    }catch(err){
        ctx.body={
            code:400,
            msg:"服务器失败",
            result:""
        }
    }
})

//获取到所有的地址信息
router.post("/getUserAddress",async (ctx,next)=>{

    try{
        let userDoc=await User.findOne({userId:ctx.session.user.userId});
        if(!!userDoc ){
            ctx.body={
                code:200,
                msg:"",
                result:userDoc.addressList,
            }
        }else{
            ctx.body={
                code:300,
                msg:"发生错误",
                result:"",
            }
        }
    }catch(err){
        ctx.body={
            code:400,
            msg:"发生错误",
            result:"",
        }
    }


})

//生成订单
router.post("/toPay",async (ctx,next)=>{
    /*生成订单的内容
    1.订单编号  保证唯一性
    2.订单购买的商品
    3.订单的收货地址  （前端传）
    4.订单状态
    5.订单的创建时间
    6.订单的总价格  （前端传）
    * */
    let userAddressId = ctx.request.body.userAddressId;
    let allPrice = ctx.request.body.allPrice;
    let creatTime = new Date().Format("yyyy-MM-dd hh-mm-ss");
    let orderID=new Date().Format("yyyyMMddhhmmss")+ctx.session.user.userId;
    //
    try{
        let userDoc= await User.findOne({userId:ctx.session.user.userId});
        let address="",goodsList=[];
        //获取收货地址
        for(let i of userDoc.addressList){
            if(i.addressId == userAddressId){
                address=i
            }
        }
        //获取商品列表
        for(let i of userDoc.cartList){
            if(i.checked == 1){
                goodsList.push(i)
            }
        }

        let orderObj={
            orderId:orderID,
            orderTotal:allPrice,
            addressInfo:address,
            goodsList:goodsList,
            orderStatus:1,
            createDate:creatTime
        }
        userDoc.orderList.push(orderObj);

        //删除购物车中的商品

        for(let i in userDoc.cartList){
            if(userDoc.cartList[i].checked == 1){
                userDoc.cartList.splice(i);
            }
        }
        if(!!await userDoc.save()){
            ctx.body={
                code:200,
                msg:"",
                result:{
                    orderID:orderID
                }
            }
        }else{
            ctx.body={
                code:300,
                msg:"订单错误",
                result:""
            }
        }
    }catch(err){
        console.log(err.message);
        ctx.body={
            code:400,
            msg:"服务器错误",
            result:""
        }
    }

})

module.exports = router